using System;
using System.Windows.Forms;
using CastleSample.Business.Client;
using CastleSample.Business.Interface;
using CastleSample.Entity;
using CastleSample.MembershipModule;
using CastleSample.UI.Core;

namespace CastleSample.Modules.Membership
{
    public class MembershipModule : ModuleBase
    {
        private MenuItemInfo m_LoginMenu;

        /// <summary>
        /// Version of the module.
        /// Just for display.
        /// </summary>
        public override string Version
        {
            get { return "1.0.0.0"; }
        }

        /// <summary>
        /// Will been called by container when load the module.
        /// </summary>
        public override bool OnLoad()
        {
            m_LoginMenu = new MenuItemInfo("File_Login", "Login", MenuLogin_Clicked);
            m_LoginMenu.ShortcutKeys = Keys.Control | Keys.L;
            ApplicationContainer.Instance.MainFrame.RegisterMenuItem(m_LoginMenu, "File", MenuItemPosition.ChildFirst);

            return true;
        }

        public override void OnStartup()
        {
            MenuLogin_Clicked(this, null);
        }

        /// <summary>
        /// Will been called by container when unload the module.
        /// </summary>
        public override void OnUnload() {}

        private void MenuLogin_Clicked(object sender, EventArgs args)
        {
            if (UserContext.Current.LoggedIn)
            {
                string userName = UserContext.Current.UserName;
                IMembershipBizService membershipService = UserContext.Current.OnlineMode ? BizServiceFactory.GetRemoteService<IMembershipBizService>() : BizServiceFactory.GetLocalService<IMembershipBizService>();
                UserContext.Current = membershipService.UserLogout(UserContext.Current);
                ApplicationContainer.Instance.EventBroker.PublishEvent("UserLoggedOut", this, new ContainerEventArgs("UserName", userName));
            }
            else
            {
                FormUserLogin formLogin = new FormUserLogin();
                formLogin.ShowDialog(ApplicationContainer.Instance.MainFrame);
                if (UserContext.Current.LoggedIn)
                {
                    ApplicationContainer.Instance.EventBroker.PublishEvent("UserLoggedIn", this, new ContainerEventArgs("UserName", UserContext.Current.UserName));
                }
            }

            m_LoginMenu.Caption = UserContext.Current.LoggedIn ? "Logout" : "Login";
        }
    }
}